<?php
/**
 * 商品处理
 * @author hdxj
 */
class GoodsController extends Controller {
	private $db;//模型
	private $cid;//栏目cid
	private $category;//栏目数据
	//构造函数
	public function __init() {
		$this -> db = K('Goods');
		$this -> cid = Q('cid', 0, 'intval');
		$this->category = Data::tree(M('category')->all(),'catname');
	}

	//商品列表
	public function index() {
//		echo $this->db->table('category')->db->table;
//		echo $this->db->table;
		//统计总条数
		$count = $this->db->count();
		//分页处理
		$page= new Page($count,3);
		$data = $this->db->limit($page->limit())->all();
		$this->assign('data',$data);
		$this->assign('page',$page->show());
		$this -> display();
	}

	//添加商品
	public function add() {
		if (IS_POST) {
			if($this->db->addGoods()){
//				$this->success('添加成功 ','index');
			}else{
//				$this->error($this->db->error);
			}
		} else {
			//分配栏目
			$this->assign('category',$this->category);
			$this-> display();
		}
	}
	//添加商品
	public function edit() {
		if (IS_POST) {
			if($this->db->editGoods()){
				$this->success('修改成功 ','index');
			}else{
				$this->error($this->db->error);
			}
		} else {
			//goods   goods_image   attr_list
			$gid = Q('gid',0,'intval');
			//商品主表数据
			$field = $this->db->find($gid);
			//商品类型id
			$gtid =M('category')->where("cid={$field['cid']}")->getField('gtid');
			$this->assign('gtid',$gtid);
			//商品详情页图片
			$goods_image=M('goods_image')->where("gid=$gid")->all();
			$this->assign('goods_image',$goods_image);
			$this->assign('field',$field);
			//分配栏目
			$this->assign('category',$this->category);
			$this-> display();
		}
	}
	//获得属性表单
	public function getAttrForm(){
		$form = K('GoodsForm');
		//获得普通属性
		$attr = $form->getAttr();
		//获得规格属性
		$spec = $form->getSpec();
		$this->assign('attr',$attr);
		$this->assign('spec',$spec);
		// p($attr);die;
		$this->display();
		exit;
	}
	//编辑商品时删除图片 Ajax
	public function delConImage(){
		$imageid= Q('imageid',0,'intval');
		$data= M('goods_image')->find($imageid);
		if(is_writable(dirname($data['big']))){
			is_file($data['big']) && @unlink($data['big']);
			is_file($data['medium']) && @unlink($data['medium']);
			is_file($data['small']) && @unlink($data['small']);
			M('goods_image')->del($imageid);
			echo 1;exit;
		}
	}
}







